package com.gitee.apanlh.util.net.http;

import com.gitee.apanlh.exp.HttpConnectionException;
import com.gitee.apanlh.exp.HttpException;
import com.gitee.apanlh.exp.HttpStreamException;
import com.gitee.apanlh.util.base.StringUtils;
import com.gitee.apanlh.util.io.IOUtils;
import com.gitee.apanlh.util.net.http.io.HttpResponseInputStream;

import java.io.Closeable;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 	HTTP客户端
 * 	<br>目前基于JDK实现
 * 	
 * 	@author Pan
 */
public class HttpClient implements Closeable {
	
	/** HTTP客户端连接 */
	private HttpURLConnection client;
	/** 请求地址 */
	private HttpUrl url;
	
	/**	
	 * 	构造函数-根据HttpURL创建
	 * 	
	 * 	@author Pan
	 * 	@param 	url		HttpUrl对象
	 */
	public HttpClient(HttpUrl url) {
		this.url = url;
	}
	
	/**
	 * 	获取HTTP客户端
	 * 	
	 * 	@author Pan
	 * 	@return	HttpURLConnection
	 */
	public HttpURLConnection getClient() {
		return client;
	}
	
	/**	
	 * 	开启客户端连接
	 * 	
	 * 	@author Pan
	 */
	public void open() {
		try {
    		// 连接
			client = (HttpURLConnection) new URL(url.get()).openConnection();
		} catch (Exception e) {
			throw new HttpConnectionException(StringUtils.format("http connection error, {} ", e.getMessage()), e);
		}
	}
	
	/**	
	 * 	获取原始输出流
	 * 	
	 * 	@author Pan
	 * 	@return	OutputStream
	 */
	public OutputStream getOutputStream() throws HttpException {
		try {
			return client.getOutputStream();
		} catch (Exception e) {
			throw new HttpStreamException(e.getMessage());
		}
	}
	
	/**
	 * 	原始输入流
	 * 	
	 * 	@author Pan
	 * 	@return	InputStream
	 */
	public InputStream getInputStream() {
		try {
			return client.getInputStream();
		} catch (Exception e) {
			throw new HttpStreamException(e.getMessage());
		}
	}
	
	/**
	 * 	原始错误输入流
	 * 	
	 * 	@author Pan
	 * 	@return	InputStream
	 */
	public InputStream getErrorInputStream() {
		try {
			return client.getErrorStream();
		} catch (Exception e) {
			throw new HttpStreamException(e.getMessage());
		}
	}
	
	/**
	 * 	根据HTTP状态来获取输入流
	 * 	<br>其中包含错误、成功输入流
	 * 	
	 * 	@author Pan
	 * 	@param 	httpStatus 	Http状态
	 * 	@return	HttpResponseInputStream
	 */
    public HttpResponseInputStream getInputStream(HttpStatus httpStatus) {
    	return new HttpResponseInputStream(this, httpStatus);
	}
	
    /**
	 * 	关闭HTTP客户端
	 * 	
	 *	@author Pan
	 */
	@Override
	public void close() {
		IOUtils.close(client);
	}

	/**	
	 * 	创建HTTP客户端
	 * 	
	 * 	@author Pan
	 * 	@param 	url		HttpUrl对象
	 * 	@return	HttpClient
	 */
	public static HttpClient create(HttpUrl url) {
		return new HttpClient(url);
	}
}
